<?php

namespace teach\service;

use Yii;

class Product
{
    /**
     * 查找产品
     * @param $condition
     * @param $page
     * @param int $pre_page
     * @return array
     */
    public function productList($condition, $page, $pre_page = 10)
    {
        $count = $this->productCount($condition);
        $data = ['total' => 0, 'total_page' => 0, 'page' => 1, 'pre_page' => $pre_page, 'lists' => []];

        if ($count) {
            $total_page = ceil( $count / $pre_page);

//            $sql = "SELECT * FROM mall_product WHERE ". $condition . " ORDER BY sort, create_time DESC LIMIT " . ($page - 1) * $pre_page . " , " . $pre_page;
            $sql = "SELECT id, aid, mid, cid, title, img, freight, old_price, level_one, is_up, count_sale, label, update_time FROM mall_product WHERE ". $condition . " ORDER BY sort, create_time DESC LIMIT " . ($page - 1) * $pre_page . " , " . $pre_page;
            $res = Yii::$app->db->createCommand($sql)->queryAll();

            $data = ['total' => $count, 'total_page' => $total_page, 'page' => $page, 'pre_page' => $pre_page, 'lists' => $res];
        }

        return $data;
    }

    /**
     * 统计产品
     * @param $condition
     * @return false|null|string
     */
    public function productCount($condition)
    {
        $sql = "SELECT COUNT(*) FROM mall_product WHERE " . $condition;
        return Yii::$app->db->createCommand($sql)->queryScalar();
    }

    /**
     * 产品详情
     * @param $param
     * @param $parameter
     * @return array|bool|false
     */
    public function productDetail($param, $parameter)
    {
        $product = $this->productMsg($param);
        if ($product['detail'] == null) {
            $product['detail'] = '';
        }
        if ($product['detail_text'] == null) {
            $product['detail_text'] = '';
        }
        $sku = $this->productSku($parameter);

        if ($sku) {
            $product['sku'] = $sku;
            return $product;
        } else {
            return false;
        }

    }

    /**
     * 获取产品信息
     * @param $condition
     * @return array|false
     */
    public function productMsg($condition)
    {
        $sql = "SELECT id, aid, mid, cid, title, img, imgs, detail, detail_text, freight, old_price, level_one, is_up, count_sale, label, update_time, parent_id, video_url FROM mall_product WHERE ". $condition;
        $res = Yii::$app->db->createCommand($sql)->queryOne();
        if ($res['video_url'] == 'undefined')
        {
            $res['video_url'] = '';
        }
        return $res;
    }

    /**
     * 获取产品sku信息
     * @param $condition
     * @return array
     */
    public function productSku($condition)
    {
        $sql = "SELECT * FROM mall_product_specs WHERE " . $condition;
        return $res = Yii::$app->db->createCommand($sql)->queryAll();
    }

}